package com.fatan.xiaopacai.util

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.doublePreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.fatan.xiaopacai.base.BaseApplication
import kotlinx.coroutines.flow.first

/**
 * @author: WangYeTong
 * @date: 2023/12/22 14:31
 * @remake:
 */
object DataStoreUtil {
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "WanAndroidDataStore")

    private val dataStore by lazy { BaseApplication.INSTANCE.dataStore }

    suspend fun <U> putData(key: String, value: U) {
        dataStore.edit { map ->
            map[getKey(key, value)] = value
        }
    }

    suspend fun <U> getData(key: String, default: U): U {
        var value: U = default
        dataStore.data.first { map ->
            value = map[getKey(key, default)] ?: default
            true
        }
        return value
    }

    private suspend fun <U> getKey(key: String, value: U): Preferences.Key<U> {
        val keyValue = when (value) {
            is Int -> intPreferencesKey(key) as Preferences.Key<U>
            is Long -> longPreferencesKey(key) as Preferences.Key<U>
            is String -> stringPreferencesKey(key) as Preferences.Key<U>
            is Float -> floatPreferencesKey(key) as Preferences.Key<U>
            is Double -> doublePreferencesKey(key) as Preferences.Key<U>
            else -> throw IllegalArgumentException("Key type is not support!")
        }
        return keyValue
    }
}